﻿using AmiDraw.Lib.Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace AmiDraw.Lib.Factory
{
    public class JsonFactory
    {
        private static JsonSerializerOptions JsonSerializerOptions = new()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };
        
        public static T LoadJson<T>(string path) where T : new()
        {
            var dir = new DirectoryInfo(Path.GetDirectoryName(path));
            if (dir.Exists is false)
                dir.Create();
            var file = new FileInfo(path);
            if (file.Exists is false)
            {
                WriteJson(path, new T());
                return new T();
            }
            return JsonSerializer.Deserialize<T>(File.ReadAllText(path),JsonSerializerOptions);


        }

        public static void WriteJson(string path, object obj)
        {
            var dir = new DirectoryInfo(Path.GetDirectoryName(path));
            if (dir.Exists is false)
                dir.Create();
            File.WriteAllText(path, JsonSerializer.Serialize(obj, JsonSerializerOptions));

        }

        public static List<MultiplotElemtentBase> LoadMultiplotElementJson(string path)
        {
            return JsonFactory.LoadJson<List<object>>(path).Select<object, MultiplotElemtentBase>(x =>
            {
                JsonElement @base = (JsonElement)x;
                switch (@base.GetProperty("Name").GetString())
                {


                    case "Text":
                        return JsonSerializer.Deserialize<TextElement>(@base.GetRawText());
                    case "Image":
                        return JsonSerializer.Deserialize<ImageElement>(@base.GetRawText());
                    case "Rectangle":
                        return JsonSerializer.Deserialize<RectangleElement>(@base.GetRawText());
                    default:
                        return new TextElement();
                };
            }).ToList();
        }
    }
}
